package com.example.deepseek.backend.controller;

import com.example.deepseek.backend.model.ChatMessage;
import com.example.deepseek.backend.service.DeepSeekService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*") // 允许所有来源的跨域请求
public class ChatController {

    @Autowired
    private DeepSeekService deepSeekService;

    // 处理文本消息
    @PostMapping("/message")
    public ResponseEntity<ChatMessage> processTextMessage(@RequestBody ChatMessage message) {
        try {
            // 获取DeepSeek的回答
            String answer = deepSeekService.processTextMessage(message.getContent());
            
            // 创建AI回复消息
            ChatMessage aiResponse = new ChatMessage("ai", answer);
            
            return ResponseEntity.ok(aiResponse);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ChatMessage("ai", "处理请求时发生错误：" + e.getMessage()));
        }
    }

    // 处理文件消息
    @PostMapping("/file")
    public ResponseEntity<ChatMessage> processFileMessage(
            @RequestParam("file") MultipartFile file) {
        try {
            // 验证文件类型
            if (!file.getContentType().equals("application/pdf") && 
                !file.getOriginalFilename().endsWith(".pdf")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ChatMessage("ai", "请上传PDF格式的文件"));
            }
            
            // 验证文件大小（5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(new ChatMessage("ai", "文件大小不能超过5MB"));
            }
            
            // 获取DeepSeek的回答
            String answer = deepSeekService.processFileMessage(file);
            
            // 创建AI回复消息
            ChatMessage aiResponse = new ChatMessage("ai", answer);
            
            return ResponseEntity.ok(aiResponse);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ChatMessage("ai", "处理文件时发生错误：" + e.getMessage()));
        }
    }
}